const childProcess = require("child_process");
const fs = require("fs");
const path = require("path");

let getPrefix = (() => {
    let prefix = "";
    return () => {
        if (prefix) {
            return prefix;
        } else {
            prefix = childProcess.execSync("npm config get prefix").toString().replace(/\s/g, "");
            return prefix;
        }
    }
})();
let getIsGlobal = (() => {
    let isGlobal = null;
    return () => {
        if (isGlobal !== null) {
            return isGlobal;
        } else {
            return isGlobal = !fs.existsSync(path.join("../node_modules"))
        }
    }
})();
let globalModule = (moduleName) => {
    let prefix = getPrefix();
    return path.join(prefix, "node_modules") + path.sep + moduleName;
}
let dealModule = (moduleName) => {
    let doAppendGlobal = getIsGlobal();
    if (doAppendGlobal) {
        return globalModule(moduleName);
    } else {
        return moduleName;
    }
}

/**
 * dealModule: 将传入的 moduleName 转换为全局安装路径（如果当前安装包下没有 node_modules ）
 */
module.exports = {
    dealModule
}